package kr.ac.mju.mdc.mjuapp.information;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import kr.ac.mju.mdc.mjuapp.R;
import kr.ac.mju.mdc.mjuapp.network.NetworkManager;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class VersionInformationViewActivity extends Activity implements OnClickListener {
	private static final int PROGRESS_DIALOG = 10;
	private static final int LOADING_SUCCESS = 11;
	private static final int LOADING_FAIL = 12;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int what = msg.what;
			switch (what) {
			case LOADING_SUCCESS:
				String version = (String) msg.obj;
				version = "v " + version;
				((TextView) findViewById(R.id.ver_info_latest_ver_name)).setText(version);

				// 현재버전과 최신버전이 같으면 업데이트 버튼 나타내기
				if (!version.equals(((TextView) findViewById(R.id.ver_info_current_ver_name)).getText())) {
					((Button) findViewById(R.id.ver_info_update_btn)).setVisibility(Button.VISIBLE);
				}
				dismissDialog(PROGRESS_DIALOG);
				break;
			case LOADING_FAIL:
				dismissDialog(PROGRESS_DIALOG);
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_network_error_weak_signal),
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// TODO Auto-generated method stub
		setContentView(R.layout.information_version_info_layout);

		((Button) findViewById(R.id.ver_info_update_btn)).setOnClickListener(this);
		setVersions();
	}

	/**
	 * 현재 설치된 앱의 버전정보와 마켓에 배포된 앱의 최신버전 정보를 가져오고 그것을 비교해서 현재 설치된 앱이 최신버전이 아니면
	 * 업데이트 버튼을 화면에 나타나게 함.
	 */
	private void setVersions() {
		String current_version = "";

		current_version = getCurrentVersion(); // 설치된 앱의 현재 버전 정보 가져옴.
		current_version = "v " + current_version;
		((TextView) findViewById(R.id.ver_info_current_ver_name)).setText(current_version);

		if (NetworkManager.checkNetwork(this)) {
			showDialog(PROGRESS_DIALOG);
			getLatestVersion(); // 마켓에 배포된 최신버전 정보 체크
		}
	}

	/**
	 * 현재 디바이스에 설치된 어플리케이션의 버전 정보를 얻어와 반환
	 * 
	 * @return - Current version information (String)
	 */
	private String getCurrentVersion() {
		String ver = "";
		try {
			PackageInfo info = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
			ver = info.versionName;
		} catch (Exception e) {
		}

		return ver;
	}

	/**
	 * 마켓에 배포된 어플리케이션의 버전 정보 체크
	 */
	private void getLatestVersion() {

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String address = getResources().getString(R.string.url_market_web);
				try {
					URL url = new URL(address);

					// connect
					HttpURLConnection con = (HttpURLConnection) url.openConnection();

					if (con != null) {
						con.setConnectTimeout(5000); // 타임아웃 설정
						con.setUseCaches(false); // 캐쉬 사용 안함.
						int resCode = con.getResponseCode();

						if (resCode == HttpURLConnection.HTTP_OK) {
							InputStream html = url.openStream();
							Source source = new Source(new InputStreamReader(html, "utf-8"));
							Element dd = (Element) source.getAllElements(HTMLElementName.DD).get(2);
							Message msg = handler.obtainMessage();
							msg.what = LOADING_SUCCESS;
							msg.obj = dd.getContent().toString();
							handler.sendMessage(msg);
						} else {
							handler.sendEmptyMessage(LOADING_FAIL);
						}
					}
				} catch (Exception e) {
					handler.sendEmptyMessage(LOADING_FAIL);
				}
			}
		});
		thread.start();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case PROGRESS_DIALOG:
			Dialog progressDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			progressDialog.setContentView(R.layout.loading_progress);
			progressDialog.setCancelable(false);
			return progressDialog;
		default:
			return null;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ver_info_update_btn:
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.url_market)));
			startActivity(intent);
			break;
		default:
			break;
		}
	}
}